package com.fm.imgreader;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author leo.li
 */
public class BinaryImageAnalyer implements DivisibleImageAnalyer {
    private Map<BufferedImage, Character> learn = new HashMap<>();

    public BinaryImageAnalyer(File store) throws IOException {
        getLearn(store);
    }

    public BinaryImageAnalyer(File train, File store, String suffix) throws IOException {
        train(train, store, suffix);
        getLearn(store);
    }

    private void train(File train, File store, String suffix) throws IOException {// TODO ImageIO.write
        File[] files = train.listFiles();
        if (files != null) {
            for (File file : files) {
                BufferedImage img = removeBackgroud(file);
                List<BufferedImage> listImg = splitImage(img);
                for (int i = 0; i < listImg.size(); ++i) {
                    ImageIO.write(listImg.get(i), suffix.toUpperCase(),
                        new File(store.getPath() + "/" + file.getName().substring(0, 4) + "-" + file.getName().charAt(i) + "." + suffix));
                }
            }
        } else {
            throw new RuntimeException(train + "不是目录或者不能访问");
        }
    }

    private void getLearn(File learnDir) throws IOException {
        File[] files = learnDir.listFiles();
        if (files != null) {
            for (File file : files) {
                String filename = file.getName();
                learn.put(ImageIO.read(file), file.getName().charAt(filename.indexOf('-') + 1));
            }
        } else {
            throw new RuntimeException(learn + "不是目录或者不能访问");
        }
    }

    private static int isBlack(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() <= 100) {
            return 1;
        }
        return 0;
    }

    private static int isWhite(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() > 600) {
            return 1;
        }
        return 0;
    }

    @Override
    public BufferedImage removeBackgroud(InputStream inputStream) throws IOException {
        BufferedImage img = ImageIO.read(inputStream);
        img = img.getSubimage(1, 1, img.getWidth() - 2, img.getHeight() - 2);
        int width = img.getWidth();
        int height = img.getHeight();
        double subWidth = (double) width / 5.0;
        for (int i = 0; i < 5; i++) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int x = (int) (1 + i * subWidth); x < (i + 1) * subWidth && x < width - 1; ++x) {
                for (int y = 0; y < height; ++y) {
                    if (isWhite(img.getRGB(x, y)) == 1)
                        continue;
                    if (map.containsKey(img.getRGB(x, y))) {
                        map.put(img.getRGB(x, y), map.get(img.getRGB(x, y)) + 1);
                    } else {
                        map.put(img.getRGB(x, y), 1);
                    }
                }
            }
            int max = 0;
            int colorMax = 0;
            for (Integer color : map.keySet()) {
                if (max < map.get(color)) {
                    max = map.get(color);
                    colorMax = color;
                }
            }
            for (int x = (int) (1 + i * subWidth); x < (i + 1) * subWidth && x < width - 1; ++x) {
                for (int y = 0; y < height; ++y) {
                    if (img.getRGB(x, y) != colorMax) {
                        img.setRGB(x, y, Color.WHITE.getRGB());
                    } else {
                        img.setRGB(x, y, Color.BLACK.getRGB());
                    }
                }
            }
        }
        return img;
    }

    private BufferedImage removeBlank(BufferedImage img) throws IOException {
        int width = img.getWidth();
        int height = img.getHeight();
        int start = 0;
        int end = 0;
        Label1:
        for (int y = 0; y < height; ++y) {
            for (int x = 0; x < width; ++x) {
                if (isBlack(img.getRGB(x, y)) == 1) {
                    start = y;
                    break Label1;
                }
            }
        }
        Label2:
        for (int y = height - 1; y >= 0; --y) {
            for (int x = 0; x < width; ++x) {
                if (isBlack(img.getRGB(x, y)) == 1) {
                    end = y;
                    break Label2;
                }
            }
        }
        return img.getSubimage(0, start, width, end - start + 1);
    }

    @Override
    public List<BufferedImage> splitImage(BufferedImage img) throws IOException {
        List<BufferedImage> subImgs = new ArrayList<>();
        int width = img.getWidth();
        int height = img.getHeight();
        List<Integer> weightlist = new ArrayList<>();
        for (int x = 0; x < width; ++x) {
            int count = 0;
            for (int y = 0; y < height; ++y) {
                if (isBlack(img.getRGB(x, y)) == 1) {
                    count++;
                }
            }
            weightlist.add(count);
        }
        for (int i = 0; i < weightlist.size(); i++) {
            int length = 0;
            while (i < weightlist.size() && weightlist.get(i) > 0) {
                i++;
                length++;
            }
            if (length > 2) {
                subImgs.add(removeBlank(img.getSubimage(i - length, 0, length, height)));
            }
        }
        return subImgs;
    }

    private Character getSingleChar(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
        int min = width * height;
        Character result = null;
        for (Map.Entry<BufferedImage, Character> entry : learn.entrySet()) {
            BufferedImage bi = entry.getKey();
            int count = 0;
            if (Math.abs(bi.getWidth() - width) > 2) {
                continue;
            }
            int widthmin = width < bi.getWidth() ? width : bi.getWidth();
            int heightmin = height < bi.getHeight() ? height : bi.getHeight();
            Label1:
            for (int x = 0; x < widthmin; ++x) {
                for (int y = 0; y < heightmin; ++y) {
                    if (isBlack(img.getRGB(x, y)) != isBlack(bi.getRGB(x, y))) {
                        count++;
                        if (count >= min) {
                            break Label1;
                        }
                    }
                }
            }
            if (count < min) {
                min = count;
                result = entry.getValue();
            }
        }
        return result;
    }

    @Override
    public String analyze(InputStream inputStream) throws IOException {
        BufferedImage img = removeBackgroud(inputStream);
        List<BufferedImage> elements = splitImage(img);
        StringBuilder result = new StringBuilder();
        for (BufferedImage bi : elements) {
            result.append(getSingleChar(bi));
        }
        return result.toString();
    }
}
